﻿using Microsoft.AspNetCore.Mvc;
using star_questionnair.DTOs;
using star_questionnair.Models;
using star_questionnair.Services.impl;

namespace star_questionnair.Controllers;

[ApiController]
[Route("response")]
public class ResponseController : ControllerBase
{
    private readonly IResponseService _responseService;

    public ResponseController(IResponseService responseService)
    {
        _responseService = responseService; // 注入服务实例
    }

    //全部提交
    [HttpPost("submitWhole")]
    public IActionResult SubmitWhole([FromBody] ResponseDTO response)
    {
        Response r = _responseService.ToEntity(response);
        var result = _responseService.SubmitWholeResponse(r);
        if (result.Id == 0)
        {
            return BadRequest(new { message = "更新失败" });
        }
        else
        {
            return Ok(new{success=true,data=result});
        }
    }
    
    //开始填写问卷
    [HttpPost("start")]
    public ActionResult<Response> Start([FromBody] ResponseDTO responseDto)
    {
        Response response = _responseService.ToEntity(responseDto);
        var result = _responseService.Start(response);
        if (result == null)
        {
            return BadRequest("Failed to process the response."); // 返回 HTTP 400 错误
        }
        return Ok(new{success=true,data=result}); // 返回 HTTP 200 响应，包含结果
    }
    
    [HttpPut("update")]
    public IActionResult Update([FromBody] ResponseDTO responseDto)
    {
        Response response = _responseService.ToEntity(responseDto);
        _responseService.UpdateResponse(response);
        return Ok("success"); // 返回成功消息
    }
    [HttpPut("updateWhole")]
    public IActionResult UpdateWholeResponse([FromBody] ResponseDTO responseDto)
    {
        Response response = _responseService.ToEntity(responseDto);
        var updatedResponse = _responseService.UpdateWholeResponse(response);
        return Ok(updatedResponse);
    }
    [HttpGet("getResponseCount/{questionId}")]
    public IActionResult GetResponseCount(int questionId)
    {
        var count = _responseService.GetResponseCountByQuestionId(questionId);
        return Ok(new{success=true,data=count});
    }
}